import React, { createContext } from 'react';
import * as effects from 'redux-saga/effects';
import useReducerAndSaga from './useReducerAndSaga';
// eslint-disable-next-line import/no-named-as-default
import Reducers from './reducers';

export const SagaContext = createContext();

const SagaContainer = props => {
  const {
    children,
    initState,
    sagas = {},
    reducers = Reducers,
    Context = SagaContext,
  } = props;

  function* saga() {
    while (true) {
      const action = yield effects.take('*');
      if (sagas[action.type]) {
        yield effects.fork(sagas[action.type], action, effects);
      }
    }
  }

  function reducer(state, action) {
    if (reducers[action.type]) {
      return reducers[action.type](state, action);
    }
    return state;
  }

  const [state, dispatch] = useReducerAndSaga(reducer, initState, saga);
  return (
    <Context.Provider
      value={{
        state,
        dispatch,
      }}
    >
      {children}
    </Context.Provider>
  );
};

export default SagaContainer;
